package pers.qianyu.month_202103.date_20210323;

import pers.qianyu.month_202101.date_20210113.NestedInteger;

import java.util.*;

/**
 * 341. 扁平化嵌套列表迭代器
 * https://leetcode-cn.com/problems/flatten-nested-list-iterator/
 *
 * @author mizzle rain
 * @date 2021-03-23 13:32
 */
public class NestedIterator implements Iterator<Integer> {
    private Deque<Iterator<NestedInteger>> st = new ArrayDeque<>();

    public NestedIterator(List<NestedInteger> nestedList) {
        st.addLast(nestedList.iterator());
    }

    @Override
    public Integer next() {
        return st.getLast().next().getInteger();
    }

    @Override
    public boolean hasNext() {
        while (!st.isEmpty()) {
            Iterator<NestedInteger> last = st.getLast();
            if (last.hasNext()) {
                NestedInteger next = last.next();
                if (!next.isInteger()) {
                    st.addLast(next.getList().iterator());
                } else {
                    ArrayList<NestedInteger> list = new ArrayList<>();
                    list.add(next);
                    st.addLast(list.iterator());
                    return true;
                }
            } else {
                st.pollLast();
            }
        }
        return false;
    }
}
